package org.jeecg.modules.company.controller;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.company.dto.ComAdminUserDto;
import org.jeecg.modules.company.service.IComAdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags="企业基本信息表")
@RestController
@RequestMapping("/company/comAdminUser")
@Slf4j
public class ComAdminController   extends JeecgController<ComAdminUserDto, IComAdminUserService> {
	
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IComAdminUserService comAdminUserService;

	/**
	 * 分页列表查询
	 *
	 * @param comUser
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "企业用户-分页列表查询")
	@ApiOperation(value="企业用户-分页列表查询", notes="企业用户-分页列表查询")
	@GetMapping(value = "/list")
	public Result<Page<ComAdminUserDto>> queryPageList(ComAdminUserDto comAdminUserDto,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Result<Page<ComAdminUserDto>> result = new Result<Page<ComAdminUserDto>>();
		Page<ComAdminUserDto> pageList = new Page<ComAdminUserDto>(pageNo,pageSize);
		pageList = comAdminUserService.page(comAdminUserDto,pageList);
		log.info("查询当前页："+pageList.getCurrent());
		log.info("查询当前页数量："+pageList.getSize());
		log.info("查询结果数量："+pageList.getRecords().size());
		log.info("数据总数："+pageList.getTotal());
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	 * 分页列表查询
	 *
	 * @param comUser
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/getDetail")
	public Result<ComAdminUserDto> queryList(@RequestBody ComAdminUserDto comAdminUserDto,
								   HttpServletRequest req) {
		Result<ComAdminUserDto> result = new Result<ComAdminUserDto>();
		if(StringUtils.isBlank(comAdminUserDto.getUserId())) {
			result.error500("缺少必要参数");
		}
		List<ComAdminUserDto> ulist = comAdminUserService.findList(comAdminUserDto);
		if(ulist!=null && ulist.size()>0) {
			Result.ok(ulist.get(0));
		}
		return result;
	}
	
	/**
	 * 新增
	 * @param request
	 * @param comAdminUserDto
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Result<ComAdminUserDto> add(HttpServletRequest request,@RequestBody ComAdminUserDto comAdminUserDto) {
		Result<ComAdminUserDto> result = new Result<ComAdminUserDto>();
		try {
			ComAdminUserDto c = new ComAdminUserDto();
	    	c.setUserId(comAdminUserDto.getUsername());
	    	List<ComAdminUserDto> u = this.comAdminUserService.findList(c);
	    	if(u!=null && u.size()>0) {
	    		result.error500("已存在相同账号,提交失败");
	    		return result;
	    	}
			String token = request.getHeader("X-Access-Token");
			if(oConvertUtils.isEmpty(token)) {
				result.error500("登录已过期,提交失败");
			   return result;
			}
			String username = JwtUtil.getUsername(token);
			comAdminUserDto.setCreateBy(username);
            comAdminUserService.save(comAdminUserDto);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	 * 删除用户
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		//如果当前登录用户删除自己，不允许；
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		if(id.equals(sysUser.getId())) {
			return Result.error("删除失败，不能删除自己帐号");
		}
		sysBaseAPI.addLog("删除用户，id： " +id ,CommonConstant.LOG_TYPE_2, 3);
		this.comAdminUserService.deleteUser(id);
		return Result.ok("删除用户成功");
	}

	/**
	 * 批量删除用户
	 */
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String id [] = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			if(id[i].equals(sysUser.getId())) {
				return Result.error("删除失败，不能删除自己帐号");
			}
		}
		
		sysBaseAPI.addLog("批量删除用户， ids： " +ids ,CommonConstant.LOG_TYPE_2, 3);
		this.comAdminUserService.deleteBatchUsers(ids);
		return Result.ok("批量删除用户成功");
	}

	/**
	  * 冻结&解冻用户
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
	public Result<ComAdminUserDto> frozenBatch(HttpServletRequest request,ComAdminUserDto dto) {
		Result<ComAdminUserDto> result = new Result<ComAdminUserDto>();
		try {
			String ids = request.getParameter("ids");
			String status = request.getParameter("status");
			List<String> list = Arrays.asList(ids.split(","));
			comAdminUserService.frozenBatch(list,status);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败"+e.getMessage());
		}
		result.success("操作成功!");
		return result;

    }

    /**
	  *  校验用户账号是否唯一<br>
	  *  可以校验其他 需要检验什么就传什么。。。
     *
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyUser(@RequestBody ComAdminUserDto sysUser) {
        Result<Boolean> result = new Result<>();
        //如果此参数为false则程序发生异常
        result.setResult(true);
        try {
            //通过传入信息查询新的用户信息
        	List<ComAdminUserDto>  user = comAdminUserService.findList(sysUser);
            if (user != null && user.size()>0) {
                result.setSuccess(false);
                result.setMessage("用户账号已存在");
                return result;
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
    public Result<ComAdminUserDto> changePassword(@RequestBody ComAdminUserDto dto) {
    	Result<ComAdminUserDto> result = new Result<ComAdminUserDto>();
    	List<ComAdminUserDto> u = this.comAdminUserService.findList(dto);
        if (u != null && u.size()>0) {
        	dto.setUserId(u.get(0).getUserId());
            comAdminUserService.changePassword(dto);
            return result.success("操作成功!");
        }else {
        	result.setSuccess(false);
            result.setMessage("用户不存在");
            return result;
        }
		
    }
	
    /**
     * 修改
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<ComAdminUserDto> edit(@RequestBody ComAdminUserDto dto) {
    	Result<ComAdminUserDto> result = new Result<ComAdminUserDto>();
    	ComAdminUserDto c = new ComAdminUserDto();
    	c.setUserId(dto.getUserId());
    	List<ComAdminUserDto> u = this.comAdminUserService.findList(c);
        if (u != null && u.size()>0) {
            comAdminUserService.edit(dto);
            return result.success("操作成功!");
        }else {
        	result.setSuccess(false);
            result.setMessage("用户不存在");
            return result;
        }
		
    }
	
}
